package com.browan.background;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Random;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.content.res.Configuration;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.util.Log;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.Animation.AnimationListener;

public class ScanActivity extends Activity
{
	private List<BackgroundData> listUrl;

	private int currentIndex;

	private String url;

	private String TAG = getClass().getSimpleName();

	private ScanView view;

	// 图片进入动画
	private Animation[] aIn;

	// 图片离开动画
	private Animation[] aOut;

	private int aniSize;

	private int aniIndex;

	private boolean isFirst;

	private PowerManager m_powerManager = null;

	private WakeLock m_wakeLock = null;

	private boolean isQuit;

	private int style;

	private boolean isStarted = false;

	private void initAnimation()
	{
		// aIn = new Animation[] { AnimationUtils.loadAnimation(this,
		// R.anim.alpha_animation_in),
		// AnimationUtils.loadAnimation(this, R.anim.scale_animation_in),
		// AnimationUtils.loadAnimation(this, R.anim.rotata_animation_in),
		// AnimationUtils.loadAnimation(this, R.anim.translate_animation_in) };
		//
		// aOut = new Animation[] { AnimationUtils.loadAnimation(this,
		// R.anim.alpha_animation_out),
		// AnimationUtils.loadAnimation(this, R.anim.scale_animation_out),
		// AnimationUtils.loadAnimation(this, R.anim.rotata_animation_out),
		// AnimationUtils.loadAnimation(this, R.anim.translate_animation_out) };

		aIn = new Animation[] { AnimationUtils.loadAnimation(this, R.anim.alpha_animation_in),
				AnimationUtils.loadAnimation(this, R.anim.scale_animation_in),

				AnimationUtils.loadAnimation(this, R.anim.translate_animation_in) };

		aOut = new Animation[] { AnimationUtils.loadAnimation(this, R.anim.alpha_animation_out),
				AnimationUtils.loadAnimation(this, R.anim.scale_animation_out),

				AnimationUtils.loadAnimation(this, R.anim.translate_animation_out) };

		aniSize = aOut.length;
	}

	private void removeReData(List<BackgroundData> list)
	{
		HashSet<BackgroundData> set = new HashSet<BackgroundData>(list);
		list.clear();
		list.addAll(set);
	}

	@Override
	protected void onResume()
	{
		m_wakeLock = m_powerManager.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK | PowerManager.ON_AFTER_RELEASE,
				TAG);
		m_wakeLock.acquire();
		super.onResume();
	}

	@Override
	protected void onStop()
	{
		if (m_wakeLock != null)
		{
			m_wakeLock.release();
		}
		super.onStop();
	}

	private int screenWidth;

	private int screenHeight;

	private DBHelper mDbHelper;

	private SQLiteDatabase mDatabase;

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		// listUrl = getIntent().getStringArrayListExtra(Intent.EXTRA_TEXT);

		// Log.e(TAG, "size1 = " + listUrl.size());
		url = getIntent().getStringExtra(Intent.EXTRA_TITLE);
		style = getIntent().getIntExtra(Background.STYLE, -1);
		initAnimation();
		mDbHelper = new DBHelper(this);
		mDatabase = mDbHelper.getDb();
		listUrl = new ArrayList<BackgroundData>();
		screenHeight = getWindowManager().getDefaultDisplay().getHeight();

		screenWidth = getWindowManager().getDefaultDisplay().getWidth();

		view = new ScanView(this);
		setContentView(view);
		currentIndex = 0;
		isFirst = true;
		isQuit = false;

		loadDataBase();

		handler.postDelayed(loadOtherData, 1000);
		m_powerManager = (PowerManager) this.getSystemService(POWER_SERVICE);
	}

	private void loadDataBase()
	{
		Cursor cursor = mDatabase.query(DBHelper.TABLE_NAME, null, DBHelper.STYLE + " = " + style, null, null, null,
				null);

		if (cursor.moveToFirst())
		{

			do
			{

				BackgroundData data = new BackgroundData();
				data.big_url = cursor.getString(cursor.getColumnIndex(DBHelper.BIG_URL));
				data.little_url = cursor.getString(cursor.getColumnIndex(DBHelper.SMALL_URL));
				listUrl.add(data);
			}
			while (cursor.moveToNext());
		}
		cursor.close();

		
//		Intent intent = new Intent();
//		
//		intent.putExtr
		
		
		if (listUrl.size() > 0)
		{
			Log.e(TAG, "load from db size = " + listUrl.size());
			
			isStarted = true;
//			handler.postDelayed(loadImage, 500);
			
			handler.post(loadImage);
		}
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig)
	{
		screenHeight = screenWidth + (screenWidth = screenHeight) * 0;
		super.onConfigurationChanged(newConfig);
	}

	Handler handler = new Handler();

	Runnable loadOtherData = new Runnable()
	{

		@Override
		public void run()
		{
			if (isQuit)
			{
				return;
			}
			try
			{
				List<BackgroundData> list = Util.getImages(url);

				if (null == list || 0 == list.size())
				{
					if (0 == listUrl.size())
					{
						ScanActivity.this.finish();
					}
				}
				else
				{
					listUrl.addAll(list);
					removeReData(listUrl);
					
					Log.e(TAG, "load from web size = " + list.size());

					Log.e(TAG, "load total size = " + listUrl.size());
					
					if (!isStarted)
						handler.post(loadImage);

					downAllPictory();

					for (BackgroundData data : list)
					{
						String bigName = Md5Tool.getMd5Value(data.big_url);

						if (!mDbHelper.isExist(DBHelper.TABLE_NAME, DBHelper.BIG_NAME + " = '" + bigName + "'"))
						{
							String smallName = Md5Tool.getMd5Value(data.little_url);
							ContentValues values = new ContentValues();
							values.put(DBHelper.BIG_NAME, bigName);
							values.put(DBHelper.SMALL_NAME, smallName);
							values.put(DBHelper.BIG_URL, data.big_url);
							values.put(DBHelper.SMALL_URL, data.little_url);
							values.put(DBHelper.STYLE, style);
							mDatabase.insert(DBHelper.TABLE_NAME, null, values);
						}

					}

				}
				// ArrayList<String> arrayList = new ArrayList<String>();
				// for (BackgroundData data : list)
				// {
				// arrayList.add(data.big_url);
				// }
				// if (arrayList.size() > 1)
				// {
				// listUrl = arrayList;
				// listUrl.addAll(arrayList);
				// Log.e(TAG, "size2 = " + listUrl.size());
				// removeReData(listUrl);
				// Log.e(TAG, "size3 = " + listUrl.size());
				// handler.postDelayed(loadImage, 500);
				// downAllPictory();
				// }
			}
			catch (Exception e)
			{
				e.printStackTrace();
			}
		}
	};

	private void downAllPictory()
	{
		new Thread(new Runnable()
		{
			@Override
			public void run()
			{
				int len = listUrl.size();

				int index = 0;

				while (index < len)
				{
					if (isQuit)
						break;

					String url = listUrl.get(index).big_url;

					index++;

					String name = Md5Tool.getMd5Value(url) + ".jpg";

					if (StoreManager.exist(name))
					{
						Log.e(TAG, name + " was exist!");
						continue;
					}

					Bitmap bitmap = StoreManager.downBitmap(url);

					if (null != bitmap)
					{
						StoreManager.storeBitmap(name, bitmap);
						bitmap.recycle();
						Log.e(TAG, index + " was stored!");
					}
					else
					{
						Log.e(TAG, url + " down failed");
					}

				}

			}
		}).start();

	}

	private Random random = new Random();

	Runnable loadImage = new Runnable()
	{
		@Override
		public void run()
		{
			if (isQuit)
			{
				return;
			}
			try
			{
				// Bitmap bitmap = BitmapFactory.decodeStream(new
				// URL(listUrl.get(currentIndex)).openStream());
				Bitmap bitmap = StoreManager.getBitmap(listUrl.get(currentIndex).big_url);

				if (null == bitmap)
				{
					throw new Exception();
				}

				if (isQuit)
				{
					return;
				}
				currentIndex = (currentIndex + 1) % listUrl.size();

				// background = bitmap;

				background = resizeBitmap(bitmap);

				handler.postDelayed(new Runnable()
				{
					@Override
					public void run()
					{
						if (isQuit)
						{
							return;
						}
						aniIndex = random.nextInt(aniSize);

						if (isFirst)
						{
							isFirst = false;
							Animation an = aIn[aniIndex];
							an.setAnimationListener(load);
							view.startAnimation(an);
							view.setBackground(background);
							view.invalidate();
						}
						else
						{
							Animation animation = aOut[aniIndex];
							animation.setAnimationListener(out);
							view.startAnimation(animation);

						}
					}
				}, 3000);
			}
			catch (Exception e)
			{
				e.printStackTrace();
				currentIndex = (currentIndex + 1) % listUrl.size();
				handler.post(loadImage);
			}
		}
	};

	private Bitmap background;

	AnimationListener load = new AnimationListener()// 载入
	{

		@Override
		public void onAnimationStart(Animation animation)
		{

		}

		@Override
		public void onAnimationRepeat(Animation animation)
		{

		}

		@Override
		public void onAnimationEnd(Animation animation)
		{
			handler.post(loadImage);
		}
	};

	AnimationListener out = new AnimationListener()// 载出
	{

		@Override
		public void onAnimationStart(Animation animation)
		{

		}

		@Override
		public void onAnimationRepeat(Animation animation)
		{

		}

		@Override
		public void onAnimationEnd(Animation animation)
		{
			Animation an = aIn[aniIndex];
			an.setAnimationListener(load);
			view.setBackground(background);
			view.invalidate();
			view.startAnimation(an);
		}
	};

	@Override
	protected void onDestroy()
	{
		mDbHelper.close();
		isQuit = true;
		view.release();
		if (null != background && !background.isRecycled())
		{
			background.recycle();
			background = null;
		}

		super.onDestroy();
	}

	private Bitmap resizeBitmap(Bitmap bmp)
	{
		float width = bmp.getWidth();
		float height = bmp.getHeight();
		float qh = screenHeight / height;

		float qw = screenWidth / width;

		if (width < screenWidth && height < screenHeight)
		{
			return bmp;
		}
		else if (qh > qw)
		{
			float width01 = qh * width;
			return Bitmap.createScaledBitmap(bmp, (int) width01, screenHeight, true);
			// Log.e(TAG, "width");
			// float height01 = qw * height;
			// return Bitmap.createScaledBitmap(bmp, screenWidth, (int)
			// height01, true);
		}
		else
		{
			float height01 = qw * height;
			return Bitmap.createScaledBitmap(bmp, screenWidth, (int) height01, true);

			// Log.e(TAG, "height");
			// float width01 = qh * width;
			// return Bitmap.createScaledBitmap(bmp, (int) width01,
			// screenHeight, true);
		}

	}

}